package org.zjvis.graph.analysis.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.zjvis.graph.analysis.service.dto.GraphFilterPipelineDTO;
import org.zjvis.graph.analysis.service.exception.BaseErrorCode;
import org.zjvis.graph.analysis.service.exception.GraphAnalysisException;
import org.zjvis.graph.analysis.service.http.UserService;
import org.zjvis.graph.analysis.service.mapper.GraphFilterPipelineMapper;

import java.util.List;

@Service
public class GraphFilterPipelineService {
    private static final Logger logger = LoggerFactory.getLogger(GraphFilterPipelineService.class);

    @Autowired
    GraphFilterPipelineMapper graphFilterPipelineMapper;

    @Autowired
    private UserService userService;

    public Long save(GraphFilterPipelineDTO dto) {
        graphFilterPipelineMapper.save(dto);
        return dto.getId();
    }

    public void update(GraphFilterPipelineDTO dto) {
        graphFilterPipelineMapper.update(dto);
    }

    public void deleteById(Long id) {
        graphFilterPipelineMapper.deleteById(id);
    }

    public GraphFilterPipelineDTO queryById(Long id) {
        return graphFilterPipelineMapper.queryById(id);
    }

    public List<GraphFilterPipelineDTO> queryByGraphId(Long id) {
        return graphFilterPipelineMapper.queryByGraphId(id);
    }

    public void deleteByGraphId(Long graphId) {
        graphFilterPipelineMapper.deleteByGraphId(graphId);
    }

    public Long queryUserById(Long id) {
        return graphFilterPipelineMapper.queryUserById(id);
    }

    public void checkAuth(Long id) {
        long userId = userService.getCurrentUserId();
        if (userId==0) {
            throw new GraphAnalysisException(BaseErrorCode.UNAUTHORIZED);
        }
        Long owner = queryUserById(id);
        if (owner == null || userService.getCurrentUserId() != owner) {
            throw new GraphAnalysisException(BaseErrorCode.GRAPH_NO_PERMISSION);
        }
    }

    public void checkPipelineAndGraph(Long id, Long graphId) {
        GraphFilterPipelineDTO pipeline = queryById(id);
        Long graph = pipeline.getGraphId();
        if (graph == null) {
            throw new GraphAnalysisException(BaseErrorCode.UNAUTHORIZED);
        }
        if (!graph.equals(graphId)) {
            throw new GraphAnalysisException(BaseErrorCode.GRAPH_FILTER_PIPELINE_RELATION_ERROR);
        }
    }


}
